// service/api/index.ts
import { useRequest } from "ahooks";
import {
  ProjectType,
  EnvironmentType,
  Environment,
  Response,
  AxiosRsp,
  QueryProject,
  QueryEnv,
  PostConfig,
  QueryConfig,
  ConfigData,
  PreviewConfig,
  BaseCinfigQueryParam,
  PostBaseConfig,
  ConfigPublishParam,
  UnConfigPublishParam,
  QueryHistoryConfigRsp,
  QueryHistoryConfigParam,
  AuthParam,
  AuthRsp,
  AuthSessionData,
  LoginParam,
  QueryTokenParam, DeleteTokenParam, UpdateTokenParam, QueryTokenRsp, AddTokenParam, TokenRow,
  ChangePasswordParam,
  QueryAcountParam,
  AddAcountParam,
  ChangeOtherPasswordParam,
  PostPermissionParam
} from "../types";
import axios from "axios";
import { gateway } from "../config";
import { message, notification } from "antd";

axios.defaults.baseURL = gateway







// export const useGetEnvironments = () => {
//   const { data, loading } = useRequest(() =>
//     new Promise<EnvironmentType[]>((resolve) => {
//       setTimeout(() => {
//        resolve([
//           { id: 1, desc: "开发环境" },
//           { id: 2, desc: "测试环境" },
//           { id: 3, desc: "生产环境" },
//         ]);
//       }, 500);
//     })
//   );
//   return { environments: data, environmentsLoading: loading };
// };
 

const request = async(call:()=>any):Promise<any> =>{

  let authData = sessionStorage.getItem("sessionData")
  if(authData){
    let authInfo:AuthSessionData = JSON.parse(authData)
    if(authInfo){
      axios.defaults.headers['Authorization'] = `Bearer ${authInfo.token}`
    }
  }
  try {
    const rsp:AxiosRsp<any> = await call()

    if(rsp?.data && rsp.data.code != 200){
      throw new Error(rsp.data.msg);
    }
    
    return rsp.data;
  } catch (rsp) {
    if(rsp?.status  == 401){
      sessionStorage.removeItem("sessionData")
      location.href = "/#/login"
      return;
    }
    if(rsp?.message == "Token is expired"){
      sessionStorage.removeItem("sessionData")
      location.href = "/#/login"
      return;
    }
    
    throw rsp;
  }
  




}
export const deleteEnv = async (data:Environment)=>{
  return request(async ()=>{
    return  await axios.post('/v1/env/delete', data)
  })
} 
export const updateEnv = async (data:Environment)=>{
  return request(async ()=>{
    return  await axios.post('/v1/env/update', data)
  })
} 

export const addEnv = async (data:Array<Environment>)=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.post('/v1/env/batch', data)
  })
} 

export const addProject = async (data:ProjectType)=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.post('/v1/project/add', data)
  })
}
export const deleteProject = async (data:ProjectType)=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.post('/v1/project/delete', data)
  })
}
export const updateProject = async (data:ProjectType)=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.post('/v1/project/update', data)
  })
}

export const queryProject = async (data:QueryProject):Promise<Response<Array<ProjectType>>>=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.get('/v1/project/list', data)
  })
}

export const queryEnv = async (data:QueryEnv):Promise<Response<Array<EnvironmentType>>>=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.get('/v1/env/list', data)
  })
}

export const postConfig = async (data:PostConfig)=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.post('/v1/config/derived/update', data)
  })
}

export const queryBaseConfig = async (data:BaseCinfigQueryParam):Promise<Response<ConfigData>>=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.get('/v1/config/base/get',{
      params:data
    })
  })
}
export const Auth = async (data:LoginParam):Promise<Response<AuthRsp>>=>{
  return request(async ()=>{
    return  await axios.post('/v1/auth', data)
  })
}

export const Login = async (data:LoginParam):Promise<Response<AuthRsp>>=>{
  return request(async ()=>{
    return  await axios.post('/login', data)
  })
}


export const postBaseConfig = async (data:PostBaseConfig)=>{
  return request(async ()=>{
    return  await axios.post('/v1/config/base/update', data)
  })
}

export const publishConfig = async (data:ConfigPublishParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/config/history/publish', data)
  })
}
export const rollbackConfig = async (data:ConfigPublishParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/config/history/publish', data)
  })
}

export const unPublishConfig = async (data:UnConfigPublishParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/config/history/unpublish', data)
  })
}

export async function tryMsg<T>(call: () => Promise<T>,fail?:(e:any)=>void):Promise<T> {
  try {
    let rsp = await call();
    notification.success({ message: "操作成功！" });
    return rsp
  } catch (e: any) {
    if (e instanceof Error) {
      notification.error({ message: e.message });
    }else if( e instanceof String){
      notification.error({ message: e });
    }else{
      notification.error({ message: "未知错误类型"+JSON.stringify(e) });
    }
    if(fail){
      fail(e);
    }
  }
}




 
export const queryConfig = async (data:QueryConfig):Promise<Response<ConfigData>>=>{
  // { loading, runAsync, error, data } =
  return request(async ()=>{
    return  await axios.get('/v1/config/derived/get', {
      params:data
    })
  })
}

export const queryPreviewConfig = async (data:PreviewConfig):Promise<Response<ConfigData>>=>{
  return request(async ()=>{
    return  await axios.post('/v1/config/derived/preview', data)
  })
}

export const queryHistoryConfig = async (data:QueryHistoryConfigParam):Promise<Response<QueryHistoryConfigRsp>>=>{
  data['page'] = data?.page ?? 0;
  data['pageSize'] = data?.pageSize ?? 10;
  return request(async ()=>{
    return  await axios.post('/v1/config/history/list', data)
  })
}

export const addToken = async (data: AddTokenParam):Promise<Response<number>>=>{
  return request(async ()=>{
    return  await axios.post('/v1/user_token/update', data)
  })
}
export const deleteToken = async (where: DeleteTokenParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/user_token/delete', where)
  })
}
export const queryToken = async (q: QueryTokenParam):Promise<Response<QueryTokenRsp>>=>{
  return request(async ():Promise<any>=>{
    console.log("queryToken",q)
    return  await axios.get('/v1/user_token/list', {
      params:q
    })
  })
}
export const updateToken = async (data: UpdateTokenParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/user_token/update', data)
  })
}
export const useGetTokens = async () =>{}
export const useGetProjects = (q:QueryProject) => {
  const { data, loading, run } = useRequest(() =>{
    return new Promise( async (resolve:(d:Array<ProjectType>)=>void,reject) => {
      try{
        let rsp = await queryProject({});
        resolve(rsp.data);
      }catch(e){
        reject(e)
      }
    });
  },{ 
      onError:(e)=>{
          notification.error({message:e.message})
      }
   });
  return { projects: data, projectsLoading: loading ,loadProjects:run};
};

export const useEnvConfig = (q:QueryConfig) => {
  console.log("useEnvConfig",q)
  const { data, loading,run } = useRequest(() =>{
    return new Promise(async (resolve) => {
      let rsp = await queryConfig(q);
      resolve(rsp.data);
    });
  });
  return { config: data, configLoading: loading,loadConfig:run };
};
 


export const useGetEnvironments = (q:QueryEnv):{environments:Array<EnvironmentType>,environmentsLoading:boolean,loadEnv:()=>void} => {
  const { data, loading,run } = useRequest(() =>
    new Promise(async (resolve) => {
      let rsp = await queryEnv(q);
      console.log("rspdata",rsp.data)
      resolve(rsp.data);
    }),{
     
    }
  );
  return {environments: data as Array<EnvironmentType>, environmentsLoading: loading,loadEnv:run };
};


export const useGetHistoryConfigs = (q:QueryHistoryConfigParam) => {
  const { data, loading,run } = useRequest(() =>
    new Promise<QueryHistoryConfigRsp>(async (resolve) => {
      let rsp = await queryHistoryConfig(q);
      resolve(rsp.data);
    }),{

    }
  );
  return { configs: data, configsLoading: loading,loadConfigs:run };
};


export const updatePassword = async (data:ChangePasswordParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/account/updatePassword', data)
  })
}
export const UpdateOtherPassword = async (data:ChangeOtherPasswordParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/account/UpdateOtherPassword', data)
  })
}

export const queryAccounts = async (data:QueryAcountParam)=>{
  return request(async ()=>{
    return  await axios.get('/v1/account/list', data)
  })
}
export const addAccount = async (data:AddAcountParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/account/add', data)
  })
}
export const deleteAccount = async (data:QueryAcountParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/account/delete', data)
  })
}
export const postPermission = async (data:PostPermissionParam)=>{
  return request(async ()=>{
    return  await axios.post('/v1/perm/set', data)
  })
}


